/**
 * 防抖函数
 * @param {Function} func
 * @param {Number} delay
 * @param {Boolean} immediate 是否立即执行
 */
export default function (func, delay = 300, immediate = true) {
  let timeout;
  return function () {
    const self = this;
    const args = arguments;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(function () {
        timeout = null;
      }, delay);
      if (callNow) func.apply(self, args);
    } else {
      timeout = setTimeout(function () {
        func.apply(self, args);
      }, delay);
    }
  };
}
